//
// Created by martin on 2/6/22.
//

#include "CountDownLatch.h"

using namespace muduo;

CountDownLatch::CountDownLatch(int count)
: mutex_(),
  cond_(mutex_),
  count_(count)
{
}

void CountDownLatch::wait()
{
    MutexLockGuard lock(mutex_);
    while (count_ > 0)
    {
        cond_.wait();
    }
}

/**
 * Count down count_ from init value to 0, then notify thread
 * waiting on the condition cond_.
 */
void CountDownLatch::countDown()
{
    MutexLockGuard lock(mutex_);
    --count_;
    if (count_ == 0)
    {
        cond_.notifyAll();
    }
}

int CountDownLatch::getCount() const {
    MutexLockGuard lock(mutex_);
    return count_;
}
